package com.demo.study.algorithm.leetcode;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * LT876
 * <a href="https://leetcode.cn/problems/middle-of-the-linked-list/description/">链表的中间结点</a>
 *
 * @author Baymax
 * @since 2024-11-15
 */
public class LT876 {

    @Test
    public void run() {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        System.out.println(middleNode(node1));
        System.out.println(middleNode1(node1));
    }

    public ListNode middleNode(ListNode head) {
        List<ListNode> nodes = new ArrayList<>();
        ListNode next = head;
        while (next != null) {
            nodes.add(next);
            next = next.next;
        }
        return nodes.get(nodes.size() / 2);
    }

    /**
     * 快慢指针
     */
    public ListNode middleNode1(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return String.valueOf(val);
        }
    }
}


